package com.android.datn.activities;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import com.android.datn.MyApplication;
import com.android.datn.R;
import com.android.datn.adapter.TrackListAdapter;
import com.android.datn.daos.TrackDAO;
import com.android.datn.helper.DBBinding;
import com.android.datn.helper.Formatter;
import com.android.datn.objects.Track;
import com.android.datn.services.AudioPlayer;
import com.android.datn.utils.AnimationFactory;
import com.android.datn.utils.AnimationFactory.FlipDirection;
import com.android.datn.utils.CommonUtil;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

@SuppressLint("NewApi")
public class ADetailMusic extends BaseActivity implements OnItemClickListener,
		OnClickListener {
	private ArrayList<Track> mArrayTrackItems;
	private TrackListAdapter mAdapter;
	private ListView mLvTracks;
	private ServiceConnection serviceConnection = new AudioPlayerServiceConnection();
	private AudioPlayer audioPlayer;
	private Intent audioPlayerIntent;
	private Timer waitForAudioPlayertimer = new Timer();
	private Handler handler = new Handler();
	private Track mTrackCurrent = null;
	private ImageView mImgFavorite, mImgList, mImgComment, mImgOption,
			mImgPrevious, mImgPlayPause, mImgNext, mImgLoop;
	private TextView mTvTitle, mTvPosition, mTvTotal;
	private SeekBar mSeekBar;
	private BroadcastReceiver audioPlayerBroadcastReceiver = new AudioPlayerBroadCastReceiver();
	private TrackDAO mTrackDAO;
	private boolean mIsTrackFirst = false;
	private ViewFlipper mViewFlipper, mViewFlipperCommentOrList;
	private boolean isLoopOn = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detail_music);
		init();
	}

	public void init() {
		mTrackDAO = TrackDAO.getInstance();
		mLvTracks = (ListView) findViewById(R.id.lv_item);
		mImgFavorite = (ImageView) findViewById(R.id.img_favorite);
		mImgNext = (ImageView) findViewById(R.id.img_next);
		mImgPlayPause = (ImageView) findViewById(R.id.img_play_pause);
		mImgPrevious = (ImageView) findViewById(R.id.img_previous);
		mImgOption = (ImageView) findViewById(R.id.img_option);
		mImgList = (ImageView) findViewById(R.id.img_list);
		mImgComment = (ImageView) findViewById(R.id.img_comment);
		mImgLoop = (ImageView) findViewById(R.id.img_loop);
		mImgLoop.setOnClickListener(this);
		mViewFlipper = (ViewFlipper) findViewById(R.id.view_flipper);
		mViewFlipperCommentOrList = (ViewFlipper) findViewById(R.id.view_flipper_kist_or_comment);
		mImgFavorite.setOnClickListener(this);
		mImgNext.setOnClickListener(this);
		mImgPlayPause.setOnClickListener(this);
		mImgPrevious.setOnClickListener(this);
		mImgOption.setOnClickListener(this);
		mImgList.setOnClickListener(this);
		mImgComment.setOnClickListener(this);
		mTvPosition = (TextView) findViewById(R.id.txt_posotion);
		mTvTitle = (TextView) findViewById(R.id.txt_title);
		mTvTotal = (TextView) findViewById(R.id.txt_total);
		mSeekBar = (SeekBar) findViewById(R.id.seekbar);
		mSeekBar.setOnSeekBarChangeListener(new TimeLineChangeListener());
		mArrayTrackItems = MyApplication.ArrayTrack;
		mAdapter = new TrackListAdapter(this, R.layout.view_item_track,
				mArrayTrackItems) {
			@Override
			public void processVote(int position) {
				Intent bindAlbumItem = new Intent(
						DBBinding.SERVICE_ALBUM_ITEM_TO_DETAIL);
				bindAlbumItem.putExtra("Position", position);
				bindAlbumItem.putExtra("Id_Category", getItem(position)
						.getIdCategory());
				ADetailMusic.this.sendBroadcast(bindAlbumItem);
			}
		};
		mLvTracks.setAdapter(mAdapter);
		mLvTracks.setOnItemClickListener(this);
		// bind to service
		audioPlayerIntent = new Intent(this, AudioPlayer.class);
		bindService(audioPlayerIntent, serviceConnection,
				Context.BIND_AUTO_CREATE);
		audioPlayerBroadcastReceiver = new AudioPlayerBroadCastReceiver();
		IntentFilter filter = new IntentFilter(DBBinding.SERVICE_DETAIL);
		registerReceiver(audioPlayerBroadcastReceiver, filter);
		IntentFilter filter1 = new IntentFilter(DBBinding.SERVICE_DETAIL_LISTEN);
		registerReceiver(audioPlayerBroadcastReceiver, filter1);
		IntentFilter filter2 = new IntentFilter(
				DBBinding.SERVICE_DETAIL_LISTEN_OFFLINE);
		registerReceiver(audioPlayerBroadcastReceiver, filter2);
		updateTrack();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	public void notification(String message, String title) {
		CommonUtil.dialogNotify(getParent().getParent(), message, title);
	}

	@Override
	public void onBackPressed() {
		finish();
	}

	private final class AudioPlayerServiceConnection implements
			ServiceConnection {
		public void onServiceConnected(ComponentName className, IBinder baBinder) {
			audioPlayer = ((AudioPlayer.AudioPlayerBinder) baBinder)
					.getService();
			startService(audioPlayerIntent);
		}

		public void onServiceDisconnected(ComponentName className) {
			audioPlayer = null;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		Intent intent = new Intent(DBBinding.INTENT_PLAY_ID);
		intent.putExtra("id", arg2);
		this.sendBroadcast(intent);
	}

	public void updateTrack() {
		waitForAudioPlayertimer.scheduleAtFixedRate(new TimerTask() {
			public void run() {
				if (audioPlayer != null) {
					handler.post(new Runnable() {
						public void run() {
							updateCurrentTrack();
						}
					});
				}
			}
		}, 10, 160);
	}

	public void updateCurrentTrack() {
		mTrackCurrent = audioPlayer.getCurrentTrack();
		if (!mIsTrackFirst) {
			mIsTrackFirst = true;
			if (mTrackDAO.getSizeByTitleAndArtist(mTrackCurrent,
					DBBinding.DB_FAVORITE) > 0) {
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorites_active);
			} else {
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorite_default);
			}
		}
		if (mTrackCurrent == null) {
		} else {
			runOnUiThread(new Runnable() {
				public void run() {
					if (mTrackCurrent.isPrepared()) {
						if (mTrackCurrent.getType() == 1) {
							mTvTitle.setText("Ä�Ã£ táº£i "
									+ mTrackCurrent.getPercentCurrent() + " %");
						} else {
							mTvTitle.setText("Music Offline");
						}
						mTvPosition.setText(Formatter
								.formatTimeFromMillis(mTrackCurrent
										.getCurrentPosition()));
						mTvTotal.setText(Formatter
								.formatTimeFromMillis(mTrackCurrent
										.getDuration()));
						mSeekBar.setMax(mTrackCurrent.getDuration());
						mSeekBar.setProgress(mTrackCurrent.getCurrentPosition());

					} else {
						mTvTitle.setText("Ä�ang táº£i...");
						mTvPosition.setText("00:00");
						mTvTotal.setText("00:00");
						mSeekBar.setMax(0);
						mSeekBar.setProgress(0);
					}
					if (audioPlayer.isPlaying()) {
						mImgPlayPause
								.setBackgroundResource(R.drawable.ic_pause);
					} else {
						mImgPlayPause.setBackgroundResource(R.drawable.ic_play);
					}
				}
			});
		}
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.img_play_pause:
			if (mTrackCurrent != null) {
				if (mTrackCurrent.isPrepared()) {
					if (audioPlayer.isPlaying()) {
						mImgPlayPause.setBackgroundResource(R.drawable.ic_play);
						audioPlayer.pause();
					} else {
						mImgPlayPause
								.setBackgroundResource(R.drawable.ic_pause);
						audioPlayer.play();
					}
				}
			}
			break;
		case R.id.img_previous:
			audioPlayer.previousTrack();
			break;
		case R.id.img_next:
			audioPlayer.nextTrack();
			break;
		case R.id.img_favorite:
			if (mTrackDAO.getSizeByTitleAndArtist(mTrackCurrent,
					DBBinding.DB_FAVORITE) > 0) {
				mTrackDAO.deleteFavorite(mTrackCurrent, DBBinding.DB_FAVORITE);

				Toast.makeText(getBaseContext(),
						"This song is deleted your favorite",
						Toast.LENGTH_SHORT).show();
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorite_default);
			} else {
				mTrackDAO.addTrack(mTrackCurrent, DBBinding.DB_FAVORITE);
				Toast.makeText(getBaseContext(),
						"This song added your favorite", Toast.LENGTH_SHORT)
						.show();
				mImgFavorite
						.setBackgroundResource(R.drawable.ic_favorites_active);
			}
			Intent bindServiceSongOfAlBum = new Intent(
					DBBinding.SERVICE_SONG_OF_ALBUM);
			this.sendBroadcast(bindServiceSongOfAlBum);
			Intent bindServiceAlbumItem = new Intent(
					DBBinding.SERVICE_ALBUM_ITEM);
			this.sendBroadcast(bindServiceAlbumItem);
			Intent bindServiceSongOfArtist = new Intent(
					DBBinding.SERVICE_SONG_OF_ARTIST);
			this.sendBroadcast(bindServiceSongOfArtist);
			break;
		case R.id.img_option:
			break;
		case R.id.img_comment:
			AnimationFactory.flipTransition(mViewFlipper,
					FlipDirection.RIGHT_LEFT);
			AnimationFactory.flipTransition(mViewFlipperCommentOrList,
					FlipDirection.RIGHT_LEFT);
			break;
		case R.id.img_list:
			AnimationFactory.flipTransition(mViewFlipper,
					FlipDirection.RIGHT_LEFT);
			AnimationFactory.flipTransition(mViewFlipperCommentOrList,
					FlipDirection.RIGHT_LEFT);
			break;
		case R.id.img_loop:
			if (isLoopOn) {
				isLoopOn = false;
				mImgLoop.setBackgroundResource(R.drawable.knob_loop_off);
			} else {
				isLoopOn = true;
				mImgLoop.setBackgroundResource(R.drawable.knob_loop_on);
			}
			break;
		default:
			break;
		}
	}

	private class TimeLineChangeListener implements
			SeekBar.OnSeekBarChangeListener {
		private Timer delayedSeekTimer;

		public void onProgressChanged(SeekBar seekBar, int progress,
				boolean fromUser) {
			if (fromUser) {
				if (mTrackCurrent.isPrepared()) {
					scheduleSeek(progress);
				}
				return;
			}
		}

		private void scheduleSeek(final int progress) {
			if (delayedSeekTimer != null) {
				delayedSeekTimer.cancel();
			}
			delayedSeekTimer = new Timer();
			delayedSeekTimer.schedule(new TimerTask() {
				@Override
				public void run() {
					audioPlayer.seek(progress);
				}
			}, 170);
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}
	}

	private class AudioPlayerBroadCastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			if (DBBinding.SERVICE_DETAIL.equals(intent.getAction())) {
				mIsTrackFirst = true;
				if (mTrackDAO.getAllTrackQuery(audioPlayer.getCurrentTrack(),
						DBBinding.DB_FAVORITE).size() > 0) {
					mImgFavorite
							.setBackgroundResource(R.drawable.ic_favorites_active);
				} else {
					mImgFavorite
							.setBackgroundResource(R.drawable.ic_favorite_default);
				}
				mAdapter.notifyDataSetChanged();
			} else if (DBBinding.SERVICE_DETAIL_LISTEN.equals(intent
					.getAction())) {
				if (!mTrackCurrent.isFavorite() && mTrackCurrent.getType() == 1) {
					Track track = (Track) intent.getBundleExtra(
							DBBinding.BUNDLEALBUM).getSerializable(
							DBBinding.ALBUM);
					// mArrayTrackItems.get(mAdapter.getPosition(track)).setListen("0");
					int position = -1;
					for (int i = 0; i < mArrayTrackItems.size(); i++) {
						if (mArrayTrackItems.get(i).getId() == track.getId()) {
							position = i;
							break;
						}
					}
					if (position != -1) {
						int count = Integer.parseInt(mArrayTrackItems.get(
								position).getListen());
						mArrayTrackItems.get(position).setListen(
								String.valueOf(count + 1));
					}
					mAdapter.notifyDataSetChanged();
				}

			}else if (DBBinding.SERVICE_DETAIL_LISTEN_OFFLINE.equals(intent
					.getAction())) {
					Track track = (Track) intent.getBundleExtra(
							DBBinding.BUNDLEALBUM).getSerializable(
							DBBinding.ALBUM);
					for(int i = 0; i< mArrayTrackItems.size(); i++){
						if(mArrayTrackItems.get(i).getArtist().toString().trim().toUpperCase().equals(
								track.getArtist().trim().toUpperCase())&&mArrayTrackItems.get(i).getTitle().toString().trim().toUpperCase().equals(
										track.getTitle().trim().toUpperCase())){
							int count = Integer.parseInt(mArrayTrackItems.get(i).getListen());
							mArrayTrackItems.get(i).setListen(String.valueOf(count + 1));
							break;
						}
					}
					mAdapter.notifyDataSetChanged();

			}
		}
	}

}
